<?php
/**
 * Created by PhpStorm.
 * User: jack Wang
 * Date: 2021/8/19
 * Time: 17:40
 */

class Article_model extends Base_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function findAll()
    {
        $query = $this->db->select('a.*,u.username,u.nickname,u.image')
            ->from('article a')
            ->join('users u', 'a.user_id = u.id')
            ->get();
        return $query->result_array();
    }

    public function findNav()
    {
        $query = $this->db->select()
            ->from('navigation')
            ->get();
        return $query->result_array();
    }

    public function findOne($id)
    {
        $query = $this->db->select('a.*,c.name as column_name,u.username,u.nickname,u.email,u.image,u.phone,u.create_time as u_time')
            ->from('article a')
            ->join('users u', 'a.user_id = u.id', 'left')
            ->join('column c', 'a.column_id = c.id', 'left')
            ->where('a.id = ', $id)
            ->where('a.user_id = c.user_id')
            ->get();
        return $query->row_array();
    }

    public function findColumn($user_id)
    {
        $query = $this->db->select('c.*')
            ->from('column c')
            ->where('c.user_id =' . $user_id)
            ->get();
        return $query->num_rows ? $query->result_array() : null;
    }

    public function findFiveArticle($user_id)
    {
        $query = $this->db->select('id,title,pageViews')
            ->from('article')
            ->where('user_id =' . $user_id)
            ->limit(5)
            ->order_by('pageViews', 'desc')
            ->get();
        return $query->result_array();
    }

    public function findNewArticle($user_id)
    {
        $query = $this->db->select('id,title')
            ->from('article')
            ->where('user_id =' . $user_id)
            ->limit(3)
            ->order_by('create_time','desc')
            ->get();
        return $query->row() ? $query->result_array() : false;
    }

    public function addComment($data)
    {
        $this->db->insert('comment', $data);
        return $this->db->affected_rows() ? true : false;
    }

    public function publish($data)
    {
        if (empty($data['id'])) {
            $this->db->insert('article', $data);
        } else {
            $this->db->update('article', $data, ['id' => $data['id']]);
        }
        return $this->db->affected_rows() ? $this->db->affected_rows() : false;
    }

    public function delArticle($id)
    {
        $this->db->delete('article', ['id' => $id]);
        return $this->db->affected_rows() ? true : false;
    }

    public function addColumn($data)
    {
        $this->db->insert('column', $data);
        return $this->db->affected_rows() ? true : false;
    }

    public function findAllArticle()
    {
        $res = $this->commonQuery('*',[],'article');
        return $res;
    }
}